import 'dart:async';
import 'dart:convert';

import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/http/index.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/utils/method_channel.dart';
import 'package:flutter_massage/values/constant.dart';
import 'package:get/get.dart';

class ApiMine extends CommonApi {
  ApiMine.info(String key) : super('sign/?a=my', {'key': key, 'signature': XydUserService.instance.signature});
  ApiMine.unread() : super('sign/?a=unread', {'key': XydUserService.key});
  ApiMine.h5Address(String kefu, String appname)
      : super('find', {'key': XydUserService.key, 'kefu': kefu, 'appname': appname});
}

/// 用户服务
class XydUserService extends GetxService {
  static XydUserService get instance => Get.find();

  /// md5加密
  String get signature {
    String hour = DateTime.now().hour.toString();
    if (hour.length == 1) {
      hour = '0$hour';
    }
    var bytes = utf8.encode("lamapi$hour");

    var digest = md5.convert(bytes);

    return digest.toString();
  }

  static String get key {
    return Storage().getString(StorageKey.userKey);
  }

  static String get kefu {
    return instance._notifierOfMineInfo.value.kefu ?? '';
  }

  ///获取idfa
  static String _idfa = '';
  static String get idfa => _idfa;
  static Future getIdfa() async {
    TrackingStatus status = await AppTrackingTransparency.requestTrackingAuthorization();
    if (status == TrackingStatus.authorized) {
      _idfa = await AppTrackingTransparency.getAdvertisingIdentifier();
    }
    await XydMethodChannel.initTdSdk();
  }

  final _notifierOfMineInfo = ValueNotifier(SettingBean());

  static ValueNotifier<SettingBean> get notifierOfMineInfo => instance._notifierOfMineInfo;

  static Future<SettingBean> getCacheMineInfoBean({bool refresh = false}) async {
    String key = Storage().getString(StorageKey.userKey);
    if (refresh || key.empty) {
      SettingBean mineInfoBean = await instance._getInfo();
      instance._notifierOfMineInfo.value = mineInfoBean;
    }
    return instance._notifierOfMineInfo.value;
  }

  Future<SettingBean> _getInfo() async {
    String key = Storage().getString(StorageKey.userKey);
    dynamic json = await CommonNet.post(ApiMine.info(key));
    return SettingBean.fromJson(json['data']);
  }

  static Future loginOut() async {
    instance._notifierOfMineInfo.value = SettingBean();
    await Storage().remove(StorageKey.userKey);
  }

  @override
  void onReady() {
    super.onReady();
    Future.delayed(const Duration(seconds: 1), () async => await getIdfa());
  }

  ///发送消息时本地生成的id
  static String get customId {
    int timestamp = DateTime.now().millisecondsSinceEpoch;
    var bytes = utf8.encode(timestamp.toString());
    var digest = md5.convert(bytes);
    return digest.toString();
  }

  ///编辑昵称
  static Future editName(String name) async {
    String phone = Storage().getString(StorageKey.userKey);
    await Storage().setString('${StorageKey.nameKey}-$phone', name);
  }

  ///获取昵称
  static String get nickName {
    String phone = Storage().getString(StorageKey.userKey);
    return Storage().getString('${StorageKey.nameKey}-$phone');
  }

  ///修改头像
  static Future editAvatar(String avatar) async {
    String phone = Storage().getString(StorageKey.userKey);
    await Storage().setString('${StorageKey.avatarKey}-$phone', avatar);
  }

  ///获取头像
  static String get avatar {
    String phone = Storage().getString(StorageKey.userKey);
    return Storage().getString('${StorageKey.avatarKey}-$phone');
  }
}

class SettingBean {
  String? mtime;
  String? version;
  // String? full;
  // String? tab;
  // String? prelogin;
  String? rank;
  Box? box;
  String? kefu;
  String? chatUnread;
  String? chatUrl;
  String? myNeedUrl;
  String? myAccount;
  String? findUrl;

  SettingBean({
    this.mtime,
    this.version,
    // this.full,
    // this.tab,
    this.rank,
    this.box,
    this.kefu,
    this.chatUnread,
    this.chatUrl,
    this.myNeedUrl,
    // this.prelogin,
    this.myAccount,
    this.findUrl,
  });

  SettingBean.fromJson(Map<String, dynamic> json) {
    if (json["mtime"] is String) {
      mtime = json["mtime"];
    }
    if (json["version"] is String) {
      version = json["version"];
    }
    // if (json["full"] is String) {
    //   full = json["full"];
    // }
    // if (json["tab"] is String) {
    //   tab = json["tab"];
    // }
    if (json["rank"] is String) {
      rank = json["rank"];
    }
    // if (json["prelogin"] is String) {
    //   prelogin = json["prelogin"];
    // }
    if (json["box"] is Map) {
      box = json["box"] == null ? null : Box.fromJson(json["box"]);
    }
    if (json["kefu"] is String) {
      kefu = json["kefu"];
    }
    if (json["chat_unread"] is String) {
      chatUnread = json["chat_unread"];
    }
    if (json["chat_url"] is String) {
      chatUrl = json["chat_url"];
    }
    if (json["my_need_url"] is String) {
      myNeedUrl = json["my_need_url"];
    }
    if (json["my_account"] is String) {
      myAccount = json["my_account"];
    }
    if (json["find_url"] is String) {
      findUrl = json["find_url"];
    }
  }
}

class Box {
  String? url;
  String? width;
  String? height;

  Box({this.url, this.width, this.height});

  Box.fromJson(Map<String, dynamic> json) {
    if (json["url"] is String) {
      url = json["url"];
    }
    if (json["width"] is String) {
      width = json["width"];
    }
    if (json["height"] is String) {
      height = json["height"];
    }
  }
}
